//
//  HMStatusPictureView.swift
//  微博
//
//  Created by 程双岐 on 16/9/25.
//  Copyright © 2016年 heima. All rights reserved.
//

import UIKit
import SDWebImage

let itemMargin: CGFloat = 5

let itemWidth = (ScrenWidth - 2 * HMHHomeTableViewCellMargin - 2 * itemMargin) / 3

class HMStatusPictureView: UICollectionView {
    
    var picUrls: [HMStatusPictureModel]?{
        didSet{
            
            guard let urls = picUrls else {
                return
            }
            
            if urls.count > 0 {
 
            numLabel.text = "\(picUrls?.count ?? 0)"

            let size = calcSize(count: picUrls?.count ?? 0)
            
            
            self.snp_updateConstraints { (make) in
                make.size.equalTo(size)
            }
                
            self.reloadData()
                
        }
            
        }
    }
    
    private lazy var numLabel: UILabel = {
       let label = UILabel(textColor: UIColor.orange, fontSize: 20)
        return label
    }()

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.minimumLineSpacing = itemMargin
        flowLayout.minimumInteritemSpacing = itemMargin
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI(){
        register(HMStatusPictureViewCell.self, forCellWithReuseIdentifier: "cellID")
        self.dataSource = self
        addSubview(numLabel)
        numLabel.snp_makeConstraints { (make) in
            make.center.equalTo(self)
        }
        
    }

    
    
    private func calcSize(count: Int) -> CGSize{
        if count == 1{
            let imageUrl = picUrls!.first!.thumbnail_pic!
            let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: imageUrl)
            if image != nil {
                
                var size = image!.size
                // 图片过窄处理
                if size.width < 80 {
                    let scaleWidth: CGFloat = 80
                    let height = scaleWidth / size.width * size.height
                    
                    let scaleHeight = height > 150 ? 150 : height
                    
                    size.width = scaleWidth
                    size.height = scaleHeight
                }
//
                let flowLayut = self.collectionViewLayout as! UICollectionViewFlowLayout
                
                flowLayut.itemSize = size
                //单张图片的大小 绑定数据时候图片比设置条目的大小要大，那么就会出现警告
                return size
            }
            
        }
        
        
        let flowLayut = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        flowLayut.itemSize = CGSize(width: itemWidth, height: itemWidth)

        
        let  cols = count > 3 ? 3 : count
        
        let rows = (count - 1) / 3 + 1
        
        let currentWidth = itemWidth * CGFloat(cols) + CGFloat(cols - 1) * itemMargin
        
        let currentHeight = itemWidth * CGFloat(rows) + CGFloat(rows - 1) * itemMargin
        
        return CGSize(width: currentWidth, height: currentHeight)
        
    }
        
        

}

extension HMStatusPictureView: UICollectionViewDataSource{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellID", for: indexPath) as! HMStatusPictureViewCell
        cell.statusPictureInfo = picUrls![indexPath.item]
        cell.backgroundColor = RandomColor()
        
        return cell
        
    }
    
}



class HMStatusPictureViewCell: UICollectionViewCell {
    
    var statusPictureInfo: HMStatusPictureModel?{
        didSet{
            
            if let url = statusPictureInfo?.thumbnail_pic{
                
            imageView.sd_setImage(with: URL(string: url), placeholderImage: UIImage(named: "timeline_image_placeholder"))
                if url.hasSuffix(".gif") {
                    gifImageView.isHidden = false
                } else {
                    gifImageView.isHidden = true
                }
                
            }

            
        }
    }
    
    private lazy var imageView: UIImageView = {
        let view = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        view.contentMode = .scaleToFill
        view.clipsToBounds = true
        return view
        
    }()
    
    //
    private lazy var gifImageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        contentView.addSubview(imageView)
        contentView.addSubview(gifImageView)
        imageView.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        gifImageView.snp_makeConstraints { (make) in
            make.bottom.equalTo(imageView)
            make.trailing.equalTo(imageView)
        }
    }
    
}

